import { createSlice } from '@reduxjs/toolkit'
import type { AppThunk } from '../store'
import { userLoginApi } from '@/service/userApi'
// import cache from '@/utils/cache'

const numSlice = createSlice({
  name: 'user',
  initialState: {
    usesrinfo: {
      id: 0,
      roleid: 0,
      name: '',
      avatar: '',
      token: '',
      routes: []
    }
  } as UserType.IState,
  reducers: {
    setUserInfo(state, { payload }: { payload: UserType.ILoginResult }) {
      state.usesrinfo = payload
      // cache().set('userinfo', payload)
    },
    clearUserInfo(state) {
      state.usesrinfo = {
        id: 0,
        roleid: 0,
        name: '',
        avatar: '',
        token: '',
        routes: []
      }
      // cache().remove('userinfo')
    }
  }
})

export const { setUserInfo, clearUserInfo } = numSlice.actions

// 用户登录
export const userLoginAction =
  (data: UserType.ILogin): AppThunk<Promise<number>> =>
  async dispatch => {
    let ret = await userLoginApi(data)
    if (ret.code === 0) {
      dispatch(setUserInfo(ret.data))
    }

    return ret.code
  }

export default numSlice.reducer
